package com.ruoyi.youtobe.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.play.domain.PlayOperaLog;
import com.ruoyi.play.mapper.PlayOperaLogMapper;
import com.ruoyi.shortplay.domain.MyChannelVideo;
import com.ruoyi.shortplay.mapper.MyChannelVideoMapper;
import com.ruoyi.until.CheckUtilsImp;
import com.ruoyi.until.ImageDownloadUtil;
import com.ruoyi.youtobe.domain.*;
import com.ruoyi.youtobe.mapper.YoutobeChannelInfoMapper;
import com.ruoyi.youtobe.mapper.YoutobeChannelVideoMapper;
import com.ruoyi.youtobe.mapper.YoutobeVideoViewCountMapper;
import com.ruoyi.youtobe.service.YoutubeVideoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/11/5
 */
@Slf4j
@Service
public class YoutubeVideoServiceImpl implements YoutubeVideoService {


    @Resource
    YoutobeChannelVideoMapper youtobeChannelVideoMapper;
    @Resource
    YoutobeChannelInfoMapper youtobeChannelInfoMapper;
    @Resource
    YoutobeVideoViewCountMapper youtobeVideoViewCountMapper;

    @Override
    public List<VideoInfoVO> getVideoInfoList(VideoInfoIO params) {
        YoutobeChannelInfo channel = youtobeChannelInfoMapper.selectYoutobeChannelInfoById(params.getId());
        List<VideoInfoVO> list = YoutubeVideoFetcher.getVideoInfoVOByIo(channel);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getVideoByChannel(VideoInfoIO params) {
        YoutobeChannelInfo channel = youtobeChannelInfoMapper.selectYoutobeChannelInfoById(params.getId());
        if (channel == null) {
            return AjaxResult.error("暂无频道数据");
        }
        List<VideoInfoVO> list = YoutubeVideoFetcher.getVideoInfoVOByIo(channel);
        if (CheckUtilsImp.listIsNotEmpty(list)) {
            for (VideoInfoVO vo : list) {
                try {
                    YoutobeChannelVideo video = CheckUtilsImp.entityToModel(vo, YoutobeChannelVideo.class);
                    //String string = vo.getPublishTime().toString();
                    video.setLocalUrl(video.getLocalUrl());
                    video.setPublishTime(new Date(vo.getPublishTime().getValue()));
                    video.setChannelId(channel.getId());
                    video.setType(channel.getType());

                    video.setTitleKey(video.getTitleKey());
                    video.setCreateBy("数据更新");
                    video.setCreateTime(new Date());
                    youtobeChannelVideoMapper.insertYoutobeChannelVideo(video);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return AjaxResult.success("新增成功 ： ");
    }


    @Override
    public AjaxResult updateMyChannelVideo() {
        //1.获取我的所有频道信息
        YoutobeChannelInfo youtobeChannelInfo = new YoutobeChannelInfo();
        //关注
        youtobeChannelInfo.setSourc("MY");
        List<YoutobeChannelInfo> channelList = youtobeChannelInfoMapper.selectYoutobeChannelInfoList(youtobeChannelInfo);
        if (CheckUtilsImp.listIsNotEmpty(channelList)) {
            for (YoutobeChannelInfo channel : channelList) {
                channel.setVideoNum(30l);
                List<VideoInfoVO> list = YoutubeVideoFetcher.getVideoInfoVOByIo(channel);
                //数据入库
                log.info("{} 频道数据开始入库 ", channel.getChannelName());
                setDataToMyChannel(list, channel);
            }
        }

        return AjaxResult.success("更新成功 ");
    }

    @Resource
    MyChannelVideoMapper myChannelVideoMapper;
    @Resource
    PlayOperaLogMapper playOperaLogMapper;

    private void setDataToMyChannel(List<VideoInfoVO> list, YoutobeChannelInfo channel) {
        try {
            //1.入我频道下的视频表
            if (CheckUtilsImp.listIsNotEmpty(list)) {
                for (VideoInfoVO vo : list) {
                    MyChannelVideo ex =   myChannelVideoMapper.selectMyChannelVideoByVcideoId(vo.getVideoId());

                    MyChannelVideo video = new MyChannelVideo();
                    video.setDefaultTitle(vo.getDefaultTitle());
                    video.setViewCount(vo.getViewCount());
                    video.setThumbnailUrl(vo.getLocalUrl());
                    video.setTitleKey(vo.getTitleKey());
                    video.setPublishTime(new Date(vo.getPublishTime().getValue()));
                    video.setState("release");
                    video.setType(channel.getType());
                    video.setVideoUrl("https://youtu.be/"+video.getVideoId());
                    if (ex ==null) {
                        video.setChannelName(channel.getChannelName());
                        video.setVideoId(vo.getVideoId());
                        video.setChannelId(channel.getId());
                        myChannelVideoMapper.insertMyChannelVideo(video);
                    }else {
                        video.setId(ex.getId());
                        https://youtu.be/HsvAz5EwdKA
                        myChannelVideoMapper.updateMyChannelVideo(video);
                    }
                    if ("SHORT_PLAY".equals(channel.getPushType())) {
                        PlayOperaLog log = playOperaLogMapper.getPlayOperaLogByVideoId(vo.getVideoId());
                        if (log==null) {
                            log = new PlayOperaLog();
                            log.setPushDate(new Date(vo.getPublishTime().getValue()));
                            log.setChannel(channel.getChannelName());
                            log.setTitle(vo.getDefaultTitle());
                            log.setVideoId(vo.getVideoId());
                            playOperaLogMapper.insertPlayOperaLog(log);
                        }else {
                            //数据修改
                            log.setPushDate(new Date(vo.getPublishTime().getValue()));
                            log.setTitle(vo.getDefaultTitle());
                            log.setPushDate(video.getPublishTime());
                            playOperaLogMapper.updatePlayOperaLog(log);
                        }
                    }
                }
            }
            //2.短剧入剪辑发布日志表
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public AjaxResult updateChannel() {
        //1.获取所有频道信息
        List<YoutobeChannelInfo> channelList = youtobeChannelInfoMapper.selectYoutobeChannelInfoList(new YoutobeChannelInfo());
        if (CheckUtilsImp.listIsNotEmpty(channelList)) {
            //频道id，频道播放列表id更新
            for (YoutobeChannelInfo info : channelList) {
                YoutubeVideoFetcher.getChannelInfo(info);
                youtobeChannelInfoMapper.updateYoutobeChannelInfo(info);
            }
        }
        return AjaxResult.success("更新成功！");
    }

    /**
     * @description: 每个频道更新近50条视频数据
     * @author: WYJ
     * @date: 2025/11/12
     * @param:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateViewCount() {
        //1.获取所有频道信息
        YoutobeChannelInfo youtobeChannelInfo = new YoutobeChannelInfo();
        //关注
        youtobeChannelInfo.setSourc("FOLLOW");
        List<YoutobeChannelInfo> channelList = youtobeChannelInfoMapper.selectYoutobeChannelInfoList(youtobeChannelInfo);
        if (CheckUtilsImp.listIsNotEmpty(channelList)) {
            for (YoutobeChannelInfo channel : channelList) {
                channel.setVideoNum(10l);
                List<VideoInfoVO> list = YoutubeVideoFetcher.getVideoInfoVOByIo(channel);
                //数据入库
                log.info("{} 频道数据开始入库 ", channel.getChannelName());
                setDataBase(list, channel);
            }
        }
        return AjaxResult.success("新增成功 ： ");
    }


    //入库操作
    void setDataBase(List<VideoInfoVO> list, YoutobeChannelInfo channel) {
        if (CheckUtilsImp.listIsNotEmpty(list)) {
            for (VideoInfoVO vo : list) {
                try {

                    //视频表数据入库
                    //根据视频id查询是否存在，存在，则更新，否则，新增
                    YoutobeChannelVideo one = youtobeChannelVideoMapper.selectVideoByVideoId(vo.getVideoId());
                    //标题关键字#提取
                    if (one != null) {
                        YoutobeChannelVideo up = new YoutobeChannelVideo();
                        up.setId(one.getId());
                        up.setViewCount(vo.getViewCount());
                        up.setUpdateTime(new Date());
                        up.setUpdateBy("数据更新");
                        //up.setLocalUrl(localPath);
                        up.setChannelId(channel.getId());
                        up.setType(channel.getType());
                        youtobeChannelVideoMapper.updateYoutobeChannelVideo(up);
                    } else {
                        YoutobeChannelVideo video = CheckUtilsImp.entityToModel(vo, YoutobeChannelVideo.class);

                        //video.setThumbnailStr(base64);
                        //String string = vo.getPublishTime().toString();
                        video.setPublishTime(new Date(vo.getPublishTime().getValue()));
                        video.setTitleKey(vo.getTitleKey());
                        video.setCreateTime(new Date());
                        video.setCreateBy("数据更新");
                        video.setLocalUrl(vo.getLocalUrl());
                        video.setChannelId(channel.getId());
                        video.setType(channel.getType());
                        youtobeChannelVideoMapper.insertYoutobeChannelVideo(video);
                    }
                    //点击量表数据入库
                    YoutobeVideoViewCount count = CheckUtilsImp.entityToModel(vo, YoutobeVideoViewCount.class);
                    count.setPublishTime(new Date(vo.getPublishTime().getValue()));
                    count.setChannelId(channel.getId());
                    count.setType(channel.getType());
                    count.setTitleKey(vo.getTitleKey());
                    count.setCreateTime(new Date());
                    count.setCreateBy("数据更新");
                    count.setLocalUrl(vo.getLocalUrl());
                    youtobeVideoViewCountMapper.insertYoutobeVideoViewCount(count);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 从URL下载图片
     */
    public static byte[] downloadImage(String imageUrl) throws Exception {
        try (InputStream inputStream = new URL(imageUrl).openStream()) {
            return IOUtils.toByteArray(inputStream);
        }
    }

    @Override
    public List<YoutobeChannelVideoVO> getVideoList(YoutobeChannelVideo params) {
        List<YoutobeChannelVideo> list = youtobeChannelVideoMapper.selectYoutobeChannelVideoList(params);
        if (CheckUtilsImp.listIsNotEmpty(list)) {
            return CheckUtilsImp.entityListToModelList(list, YoutobeChannelVideoVO.class);
        }

        return new ArrayList<>(16);
    }

    @Override
    public AjaxResult downloadPicByUrl(Integer num) {
        List<YoutobeChannelVideo> list = youtobeChannelVideoMapper.getVideoNoPic(num);
        if (CheckUtilsImp.listIsNotEmpty(list)) {
            for (YoutobeChannelVideo vo : list) {
                String localPath = null;
                try {
                    localPath = ImageDownloadUtil.downloadImage(vo.getThumbnailUrl());
                } catch (Exception e) {
                    youtobeChannelVideoMapper.deleteYoutobeChannelVideoById(vo.getId());
                    continue;
                    //e.printStackTrace();
                }
                vo.setLocalUrl(localPath);
                youtobeChannelVideoMapper.updateYoutobeChannelVideo(vo);
            }
        }
        //"/profile" + s;
        return AjaxResult.success("修改成功");
    }

    /**
     * 下载图片并返回本地路径
     *
     * @param imageUrl 网络图片URL
     * @return 本地图片路径
     */
    public String downloadAndSaveImage(String imageUrl) throws Exception {
        //"/profile" + s;
        return ImageDownloadUtil.downloadImage(imageUrl);
    }

    /**
     * 批量下载图片
     *
     * @param imageUrls 图片URL列表
     * @return 本地图片路径列表
     */
    public List<String> batchDownloadImages(List<String> imageUrls) {
        List<String> localPaths = new ArrayList<>();
        for (String imageUrl : imageUrls) {
            try {
                String localPath = ImageDownloadUtil.downloadImage(imageUrl);
                localPaths.add(localPath);
            } catch (Exception e) {
                // 记录错误但继续处理其他图片
                log.error("下载图片失败: {}", imageUrl, e);
                localPaths.add(null); // 或者使用默认图片
            }
        }
        return localPaths;
    }
}
